import { acceptHMRUpdate, defineStore } from 'pinia';

interface BasicUserInfo {
  /**
   * 头像
   */
  avatar: string;
  /**
   * 用户id
   */
  userId: string;
  /**
   * 用户名
   */
  username: string;
}

interface AccessState {
  /**
   * 用户信息
   */
  userInfo: BasicUserInfo | null;
  /**
   * 登录 accessToken
   */
  accessToken: null | string;
  /**
   * 是否已经检查过权限
   */
  isAccessChecked: boolean;
  /**
   * 登录是否过期
   */
  loginExpired: boolean;
}

/**
 * @zh_CN 用户信息相关
 */
export const useUserStore = defineStore('wos-user', {
  actions: {
    setAccessToken(token: null | string) {
      this.accessToken = token;
    },
    setIsAccessChecked(isAccessChecked: boolean) {
      this.isAccessChecked = isAccessChecked;
    },
    setLoginExpired(loginExpired: boolean) {
      this.loginExpired = loginExpired;
    },
    setUserInfo(userInfo: BasicUserInfo | null) {
      // 设置用户信息
      this.userInfo = userInfo;
    },
  },
  persist: true,
  state: (): AccessState => ({
    accessToken: '',
    isAccessChecked: false,
    loginExpired: false,
    userInfo: null,
  }),
});

// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
  hot.accept(acceptHMRUpdate(useUserStore, hot));
}
